package com.javasm.filter;

import com.alibaba.fastjson.JSON;
import com.javasm.entity.ReturnCodeEnum;
import com.javasm.entity.ReturnResult;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @version 0.1
 * @className: MyFilter2
 * @description:
 * @author: gfs
 * @date: 2025/6/25 11:14
 * @since: jdk17
 */
//@WebFilter("/*")
public class MyFilter2 implements Filter {



    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpSession session = req.getSession();
        Object loginUser = session.getAttribute("loginUser");
        //白名单 whiteList  允许列表
        //黑名单 blackList  阻止列表

        //请求路径读取方式
        String requestURI = req.getRequestURI();
        String servletPath = req.getServletPath();
//        System.out.println(requestURI);
//        System.out.println(servletPath);

        if("/login".equals(servletPath)){
            chain.doFilter(req,resp);
        }else{
            if(loginUser!=null){
                chain.doFilter(req,resp);
            }else{

                ReturnResult returnResult = new ReturnResult();

                returnResult.setCode(ReturnCodeEnum.NOT_LOGIN.getCode());
                returnResult.setMsg(ReturnCodeEnum.NOT_LOGIN.getMsg());

                //用输出流输出JSON字符串
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                writer.print(JSON.toJSONString(returnResult));
                writer.close();
            }
        }




    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }


}
